//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.Cloud.Verifications.Implentations
{
    using System;
    using Microsoft.ServiceBus.Messaging;
    using Preflight.Model;
    using Preflight.Verifications;

    public class ServiceBusSubscriptionReadVerification : ServiceBusVerificationBase<ServiceBusSubscriptionReadVerificationDescription>
    {
        protected override bool OnBeforeVerification(VerificationResult result)
        {
            return VerificationExtensions.MustSatisfy(
                () => base.OnBeforeVerification(result),
                () => this.Description.GetSubscriptionName.SuccessfullyYieldsNonNullOrEmptyValue("Subscription name", result));
        }

        protected override void AddVerificationDetail(VerificationResult result)
        {
            base.AddVerificationDetail(result);
            result.AddMessage(MessageType.Information, "Subscription name: {0}", this.Description.GetSubscriptionName());
        }

        protected override void ExecuteVerification(VerificationResult result)
        {
            try
            {
                var receiver = this.CreateMessageReceiver(SubscriptionClient.FormatSubscriptionPath(this.Description.GetTopicName(), this.Description.GetSubscriptionName()));
                var message = receiver.Receive(TimeSpan.FromSeconds(20));
                if (message != null)
                {
                    message.TryDefer();
                }

                receiver.Close();
            }
            catch (Exception exception)
            {
                result.AddException(exception);
            }
        }
    }
}
